package stru1.day8;

import java.util.StringJoiner;

/**
 * 83. 删除排序链表中的重复元素
 */
public class Solution2 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(1, new ListNode(1, new ListNode(2)));
        print(deleteDuplicates(head1));

        ListNode head2 = new ListNode(1, new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(3)))));
        print(deleteDuplicates(head2));
    }

    /**
     * 一次遍历
     */
    public static ListNode deleteDuplicates(ListNode head) {
        ListNode curr = head;
        while (curr != null) {
            int currVal = curr.val; //currVal指向当前节点的值
            ListNode _cuur = curr; //_cuur指向当前节点的引用
            while (curr.next != null && curr.next.val == currVal) { //tempList最终指向与当前节点值相异的节点的上一节点
                curr = curr.next;
            }
            _cuur.next = curr.next;
            curr = _cuur.next;
        }
        return head;
    }

    private static void print(ListNode list) {
        StringJoiner sj = new StringJoiner(",", "[", "]");
        while (list != null) {
            sj.add(String.valueOf(list.val));
            list = list.next;
        }
        System.out.println(sj);
    }

}
